import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Notification } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, randomStr } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, code: code, randomStr: randomStr })
        .then((response) => {
          const { token, nickname, lastLoginTime } = response.data

          commit('SET_TOKEN', token)
          setToken(token)

          let loginMessage
          if (lastLoginTime) {
            loginMessage = `<p>尊敬的 ${nickname}，欢迎回来！<br/>上次登录时间: ${lastLoginTime.replace('T', ' ')}</p>`
          } else {
            loginMessage = `<p>尊敬的 ${nickname}，欢迎来到我们的平台！<br/>期待与您一起探索更多功能。</p>`
          }

          Notification.success({
            title: '登录成功',
            dangerouslyUseHTMLString: true,
            message: loginMessage,
            offset: 50
          })

          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response

          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          const { username, avatar } = data

          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)

          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')

          Notification.success({
            title: '退出登录',
            dangerouslyUseHTMLString: true,
            message: '成功退出登录! 欢迎再次回来!',
            offset: 50
          })

          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
